package com.redsun.smallworld.gl.glcontroller;

import com.jogamp.opengl.util.texture.Texture;
import com.jogamp.opengl.util.texture.TextureData;
import com.jogamp.opengl.util.texture.TextureIO;

import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLProfile;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.Buffer;

/**
 * Created by zhebinwang on 2017/6/2.
 * 用来控制纹理
 * 首先把所有的文理全部读入软件
 */
public class TextureController {
    public static  int [] textureid =new int[5];

    //单例
    private final static TextureController textureController =new TextureController();


    private TextureController(){}

    public  static TextureController  getInterface(){

        return textureController;
    }

    //绑定单一纹理，并指定他的编号。
    public int bindTexture(String filename,int texindex,GL2 gl2){

        File f=new File(filename);
        Texture texture;
        InputStream is = null;
        try {
            //is = url.openStream();
            is=new FileInputStream(f);
        } catch (IOException e) {
            e.printStackTrace();
        }
        TextureData data = null;
        try {
            data = TextureIO.newTextureData(GLProfile.getDefault(), is, GL.GL_RGBA, GL.GL_RGBA, true, null);
        } catch (IOException e) {
            e.printStackTrace();
        }
        texture= TextureIO.newTexture(data);
        Buffer ff=data.getBuffer();
        gl2.glBindTexture(GL.GL_TEXTURE_2D, texindex  );// 绑定纹理
       // ff.rewind();
        gl2.glPixelStorei(gl2.GL_UNPACK_ALIGNMENT,1);
        gl2.glTexImage2D(GL2.GL_TEXTURE_2D, 0, GL2.GL_RGB, texture.getWidth(),
                texture.getHeight(), 0, GL2.GL_RGB, GL2.GL_UNSIGNED_BYTE,
                ff.rewind());

        gl2.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_LINEAR);
        gl2.glTexParameteri(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_LINEAR);
        return 0;
    }
    /**系统初始化 初始化所有纹理内容***/
    public int initTexture(GL2 gl2){

        bindTexture("/Users/zhebinwang/Documents/WechatIMG2392.jpeg",textureid[1]  ,gl2);
        bindTexture("/Users/zhebinwang/Documents/94cad1c8a786c917658fffd8c03d70cf3ac75746.jpg",textureid[0]  ,gl2);
        bindTexture("/Users/zhebinwang/dev/srces/RedSun/smallworld/target/pic/sdgfheader1.jpg",textureid[2]  ,gl2);
        bindTexture("/Users/zhebinwang/dev/srces/RedSun/smallworld/target/pic/ui3.jpg",textureid[3]  ,gl2);


        /* bindTexture("pic/WechatIMG2392.jpeg",textureid[1],gl2);
        bindTexture("pic/94cad1c8a786c917658fffd8c03d70cf3ac75746.jpg",textureid[0],gl2);
*/
        return 0;
    }
}
